﻿using System.Reflection;
using Devonline.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Devonline.Database.PostgreSQL;

public static class ServiceExtensions
{
    /// <summary>
    /// 注册数据库上下文
    /// </summary>
    /// <param name="services">依赖注入服务容器</param>
    /// <param name="appSetting">基础配置项</param>
    /// <returns></returns>
    public static IServiceCollection AddDbContext<TDbContext>(this IServiceCollection services, AppSetting appSetting) where TDbContext : DbContext
    {
        if (!string.IsNullOrWhiteSpace(appSetting.ApplicationDbContext))
        {
            var assembly = appSetting.MigrationsAssembly ?? Assembly.GetCallingAssembly().FullName;
            services.AddDbContext<TDbContext>(builder => builder.UseNpgsql(appSetting.ApplicationDbContext, options => options.MigrationsAssembly(assembly)), appSetting.ServiceLifetime);
        }

        return services;
    }
    /// <summary>
    /// 注册数据库上下文
    /// </summary>
    /// <param name="services">依赖注入服务容器</param>
    /// <param name="connectionString">数据库连接字符串</param>
    /// <param name="migrationsAssembly">数据迁移作用的程序集</param>
    /// <param name="contextLifetime">数据库上下文的生命周期</param>
    /// <returns></returns>
    public static IServiceCollection AddDbContext<TDbContext>(this IServiceCollection services, string? connectionString = default, string? migrationsAssembly = default, ServiceLifetime contextLifetime = ServiceLifetime.Scoped) where TDbContext : DbContext
    {
        if (!string.IsNullOrWhiteSpace(connectionString))
        {
            var assembly = migrationsAssembly ?? Assembly.GetCallingAssembly().FullName;
            services.AddDbContext<TDbContext>(builder => builder.UseNpgsql(connectionString, options => options.MigrationsAssembly(assembly)), contextLifetime);
        }

        return services;
    }

    /// <summary>
    /// 注册数据库上下文创建对象
    /// </summary>
    /// <param name="builder">依赖注入服务容器</param>
    /// <param name="connectionString">数据库连接字符串</param>
    /// <param name="migrationsAssembly">数据迁移作用的程序集</param>
    /// <returns></returns>
    public static DbContextOptionsBuilder Build(this DbContextOptionsBuilder builder, string? connectionString = default, string? migrationsAssembly = default)
    {
        if (!string.IsNullOrWhiteSpace(connectionString))
        {
            var assembly = migrationsAssembly ?? Assembly.GetCallingAssembly().FullName;
            return builder.UseNpgsql(connectionString, options => options.MigrationsAssembly(assembly));
        }

        return builder;
    }
}